<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :http-request="upload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <el-progress v-if="showprogress" class="progress" type="circle" :percentage="percent" />
  </el-upload>
</template>

<script>
// 引入必要的COS模块
const COS = require('cos-js-sdk-v5')
// 实例化对象
const cos = new COS({
  SecretId: 'AKID75ohMmxta2FDyVnp57uSkpgHdjaEeGgr', // 身份识别ID
  SecretKey: 'yg9NM5cuxnqfFZeXDftteASq46wd9QSE' // 身份秘钥
})
export default {
  name: 'UploadImg',
  props: {
    imgUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: '',
      percent: 0,
      showprogress: false
    }
  },
  watch: {
    imgUrl() {
      this.imageUrl = this.imgUrl
      console.log(this.imgUrl)
    }

  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    upload(res) {
      this.showprogress = true
      console.log(res.file)
      // 执行上传操作
      cos.putObject({
        Bucket: 'lzc-1313015834', /* 存储桶 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: res.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: res.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(progressData)
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        // 上传成功之后
        if (data.statusCode === 200) {
          this.imageUrl = `https:${data.Location}`
          this.$emit('get-url', this.imageUrl)
          this.showprogress = false
        }
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .progress{
    position: absolute;
    display: flex;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    background: #fff;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

